﻿using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Services.Description;
using S1.Filters;
using S1.Models;
using S1.Services;

namespace S1.Controllers
{
    [BasicAuthenticationAttribute("staff", "BCLyon2024")]
    public class ProductsController : ApiController
    {
        // GET: api/Products
        public AppResult<IEnumerable<Product>> Get()
        {
            var result = new AppResult<IEnumerable<Product>>();
            using (var service = new ProductService())
            {
                var products = service.GetAll();
                result.Data = products;
            }
            return result;
        }

        // GET: api/Products/5
        public AppResult<Product> Get(int id)
        {
            var result = new AppResult<Product>();

            using (var service = new ProductService())
            {
                var product = service.Get(id);
                result.Data = product;
            }
            return result;
        }

        // POST: api/Products
        /// <summary>
        /// 新增产品
        /// </summary>
        /// <param name="product">新增产品对象</param>
        /// <returns></returns>
        public AppResult Post([FromBody] Product product)
        {
            var result = new AppResult();
            if (ModelState.IsValid)
            {
                try
                {
                    using (var service = new ProductService())
                    {
                        service.Add(product);
                    }
                }
                catch (System.Exception ex)
                {
                    result.IsSuccess = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.ModelError(ModelState);
            }
            return result;
        }

        // PUT: api/Products/5
        public AppResult Put(int id, [FromBody] Product product)
        {
            var result = new AppResult();
            try
            {
                using (var service = new ProductService())
                {
                    service.Update(id, product);
                }
            }
            catch (System.Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
            }
            return result;

        }

        // DELETE: api/Products/5
        public AppResult Delete(int id)
        {
            var result = new AppResult();
            try
            {
                using (var service = new ProductService())
                {
                    service.Remove(id);
                }
            }
            catch (System.Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
            }
            return result;
        }
    }
}
